package com.kelaite.procurement.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kelaite.procurement.common.RetCodeEnum;
import com.kelaite.procurement.constants.UserTypeEnum;
import com.kelaite.procurement.dto.CompanyDTO;
import com.kelaite.procurement.dto.UserDTO;
import com.kelaite.procurement.entity.TCompany;
import com.kelaite.procurement.entity.TUser;
import com.kelaite.procurement.exception.BusinessException;
import com.kelaite.procurement.repository.UserRepository;
import com.kelaite.procurement.service.UserService;
import com.kelaite.procurement.utils.ConvertUtil;
import com.kelaite.procurement.utils.EncryptUtils;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserRepository userRepository;

	@PersistenceContext
	private EntityManager em;

	@Transactional
	@Override
	public TUser save(TUser persistence) {
		return this.userRepository.save(persistence);
	}

	@Override
	public TUser getObject(Long id) {
		return this.userRepository.findOne(id);
	}

	@Override
	public List<TUser> getAll() {
		return this.userRepository.findAll();
	}

	@Transactional
	@Override
	public void deleteByObject(TUser persistence) {
		this.userRepository.delete(persistence);
	}

	@Transactional
	@Override
	public void deleteByPrimaryKey(Long id) {
		this.userRepository.delete(id);
	}

	@SuppressWarnings({ "unchecked" })
	@Override
	public List<TUser> getByProperty(String property, Object value) {
		Session session = (org.hibernate.Session) em.getDelegate();
		Criteria criteria = session.createCriteria(TUser.class).add(
				Restrictions.eq(property, value));
		return criteria.list();
	}

	@Override
	public UserDTO login(UserDTO user) {
		if (StringUtils.isBlank(user.getUsername())) {
			throw new BusinessException(RetCodeEnum.USERNAME_NULL);
		}

		if (StringUtils.isBlank(user.getPassword())) {
			throw new BusinessException(RetCodeEnum.PASSWORD_NULL);
		}

		TUser dbUser = userRepository.findByUsername(user.getUsername());
		if (null == dbUser) {
			throw new BusinessException(RetCodeEnum.USER_NOT_EXSIST);
		}

		String password = EncryptUtils.encryptSalt(user.getPassword());
		if (!StringUtils.equals(password, dbUser.getPassword())) {
			throw new BusinessException(RetCodeEnum.PASSWORD_ERROR);
		}

		user = ConvertUtil.convertObj(dbUser, UserDTO.class);
		if (null != dbUser.gettCompany()) {
			user.settCompany(ConvertUtil.convertObj(dbUser.gettCompany(),
					CompanyDTO.class));
		}
		return user;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TUser> getUsersByCompany(TCompany company, TUser user) {
		Session session = (org.hibernate.Session) em.getDelegate();
		List<TUser> userList = new ArrayList<TUser>();
		if (Integer.parseInt(String.valueOf(user.getType())) == UserTypeEnum.SUPPLIER
				.getVal()) {
			// 针对供应商,可查看和当前client关联的用户 (当前用户为 vendor)
			Criteria criteria = session
					.createCriteria(TUser.class)
					.add(Restrictions.eq("tCompany", company))
					.add(Restrictions.ne("type", Short.parseShort(String
							.valueOf(UserTypeEnum.CLIENT.getVal()))))
					.addOrder(org.hibernate.criterion.Order.asc("id"));
			userList = criteria.list();
		} else {
			userList.add(user);
		}
		return userList;
	}

	@Override
	public Long countByTCompany(TCompany tCompany) {
		// TODO Auto-generated method stub
		return userRepository.countByTCompany(tCompany);
	}

	@Override
	public TUser findByUsername(String username) {
		// TODO Auto-generated method stub
		return userRepository.findByUsername(username);
	}

	@Override
	public TUser findByTCompanyAndIsCompanyAdmin(TCompany company,
			Integer isCompanyAdmin) {
		// TODO Auto-generated method stub
		return userRepository.findByTCompanyAndIsCompanyAdmin(company, isCompanyAdmin);
	}

	@Override
	public boolean updateChangeUser(String realName, String mobilePhone,
			Long companyId, String roleIds, Long id) {
		
		boolean updateSuccess;
		try
		{
			this.userRepository.updateChangeUser(realName, mobilePhone, companyId, roleIds, new Date(), id);
			updateSuccess=true;
		}
		catch(Exception e)
		{
			updateSuccess=false;
		}
		
		return updateSuccess;
	}

	
	
}
